<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="vue-vuex"><meta name="keywords" content="vue vuex"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>vue-vuex | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#4-state"><span class="toc-number">1.</span> <span class="toc-text">4.state</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#4-1-mapState"><span class="toc-number">1.1.</span> <span class="toc-text">4.1 mapState</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5-getter"><span class="toc-number">2.</span> <span class="toc-text">5.getter</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#5-1-mapgetter"><span class="toc-number">2.1.</span> <span class="toc-text">5.1 mapgetter</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#6-mutation"><span class="toc-number">3.</span> <span class="toc-text">6.mutation</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#7-action"><span class="toc-number">4.</span> <span class="toc-text">7.action</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#8-module"><span class="toc-number">5.</span> <span class="toc-text">8.module</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#8-1%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4"><span class="toc-number">5.1.</span> <span class="toc-text">8.1命名空间</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">vue-vuex</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-07-19</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">2.6k</span><span class="post-meta__separator">|</span><span>阅读时长: 10 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>Vuex 是一个专为 大型Vue.js 应用程序开发的<strong>状态管理模式</strong></p>
<p>1.简单来说，vuex就是用来集中管理组件的数据的(多组件共享的数据)。</p>
<p><strong>数据驱动视图，动作(action)更改数据</strong>，是一个环形单向数据流。</p>
<p>每一个 Vuex 应用的核心就是 store(数据仓库)。</p>
<p>2.vuex需要安装</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">npm install vuex -S</span><br></pre></td></tr></table></figure>

<p>3.在vue应用的下面会多出来一个store的文件夹，在里面使用vuex。首先会在里面的index.js里面创建仓库对象。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> Vuex.Store(&#123; <span class="comment">//data</span></span><br><span class="line"><span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">num</span>:<span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line"> getters,</span><br><span class="line"> <span class="comment">//methods,在mutation里处理状态</span></span><br><span class="line">  <span class="attr">mutations</span>: &#123;</span><br><span class="line">    <span class="function"><span class="title">addnum</span>(<span class="params">state</span>)</span>&#123;</span><br><span class="line">      state.num++;</span><br><span class="line">    &#125;</span><br><span class="line"> <span class="comment">//异步方法</span></span><br><span class="line"> actions,</span><br><span class="line"> <span class="comment">//模块</span></span><br><span class="line"> <span class="attr">modules</span>: &#123;</span><br><span class="line">  buyCar</span><br><span class="line"> &#125; &#125;)</span><br></pre></td></tr></table></figure>

<p>在state里面添加全局数据，在mutation里面添加全局方法，修改数据。组件想要调用此方法，需要使用this.$store.<strong>commit</strong>(‘addnum’);进行调用。通过$store.state.num获得数据。</p>
<p>Vuex 通过 <code>store</code> 选项，提供了一种机制将状态从根组件“注入”到每一个子组件中（需调用 <code>Vue.use(Vuex)</code>）：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  <span class="attr">el</span>: <span class="string">&#x27;#app&#x27;</span>,</span><br><span class="line">  <span class="comment">// 把 store 对象提供给 “store” 选项，这可以把 store 的实例注入所有的子组件</span></span><br><span class="line">  store,<span class="comment">//es6的property简化写法</span></span><br><span class="line">  <span class="attr">components</span>: &#123; Counter &#125;,</span><br><span class="line">  <span class="attr">template</span>: <span class="string">`</span></span><br><span class="line"><span class="string">    &lt;div class=&quot;app&quot;&gt;</span></span><br><span class="line"><span class="string">      &lt;counter&gt;&lt;/counter&gt;</span></span><br><span class="line"><span class="string">    &lt;/div&gt;</span></span><br><span class="line"><span class="string">  `</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>通过在根实例中注册 <code>store</code> 选项，该 store 实例会注入到根组件下的所有子组件中，且子组件能通过 <code>this.$store</code> 访问到。不需要每次都导入store</p>
<h5 id="4-state"><a href="#4-state" class="headerlink" title="4.state"></a><strong>4.state</strong></h5><p>在组件里的应用，一般放在computed里面当做一个函数，返回一个在state里面的数据，如</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">msg:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="keyword">return</span> $store.state.num;&#125;</span><br></pre></td></tr></table></figure>

<h6 id="4-1-mapState"><a href="#4-1-mapState" class="headerlink" title="4.1 mapState"></a>4.1 mapState</h6><p>简化我们获取数据的方式，mapState的作用就是返回一个对象，这个对象可以直接丢给computed</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapState &#125; <span class="keyword">from</span> <span class="string">&#x27;vuex&#x27;</span><span class="comment">//需要引用</span></span><br><span class="line">   <span class="comment">// computed: &#123;//旧方法</span></span><br><span class="line">    <span class="comment">//     userList: function() &#123;</span></span><br><span class="line">    <span class="comment">//         return this.$store.state.userList;</span></span><br><span class="line">    <span class="comment">//     &#125;,</span></span><br><span class="line">    <span class="comment">//     goodsList: function() &#123;</span></span><br><span class="line">    <span class="comment">//         return this.$store.state.goodsList;</span></span><br><span class="line">    <span class="comment">//     &#125;</span></span><br><span class="line">    <span class="comment">// &#125;</span></span><br><span class="line"><span class="attr">computed</span>: mapState(&#123;</span><br><span class="line">        <span class="attr">title</span>: <span class="function"><span class="params">state</span> =&gt;</span> state.tital,</span><br><span class="line">        <span class="function"><span class="title">userList</span>(<span class="params">state</span>)</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> state.userList;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function"><span class="title">goodsList</span>(<span class="params">state</span>)</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> state.goodsList;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;),</span><br></pre></td></tr></table></figure>

<p>如果state上有某个属性，可以直接赋值：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">computed: mapState(&#123;</span><br><span class="line">    <span class="attr">title</span>: <span class="string">&#x27;title&#x27;</span>,</span><br><span class="line">    <span class="attr">userList</span>: <span class="string">&#x27;userList&#x27;</span>,</span><br><span class="line">    <span class="attr">goodsList</span>: <span class="string">&#x27;goodsList&#x27;</span></span><br><span class="line">&#125;),</span><br></pre></td></tr></table></figure>

<p>如果mapState属性的名字和state中属性的名字相同的话，就可以采用下面更简单的写法：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">computed: mapState([<span class="string">&#x27;title&#x27;</span>, <span class="string">&#x27;goodsList&#x27;</span>, <span class="string">&#x27;userList&#x27;</span>])</span><br></pre></td></tr></table></figure>

<p>有些复杂数据还是推荐使用第一种。</p>
<p>或者如果你是用了模块的话，需要在mapState的第一个参数里面传入这个模块文件，在第二个参数里面获取这个模块的state</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">computed: &#123;</span><br><span class="line">  ...mapState(<span class="string">&#x27;some/nested/module&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">a</span>: <span class="function"><span class="params">state</span> =&gt;</span> state.a,</span><br><span class="line">    <span class="attr">b</span>: <span class="function"><span class="params">state</span> =&gt;</span> state.b</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>



<h5 id="5-getter"><a href="#5-getter" class="headerlink" title="5.getter"></a><strong>5.getter</strong></h5><p>相当于store的一个计算属性，就是对state的数据进行计算，当组件需要取到state的属性然后进行计算得到想要的结果的时候，计算的过程可以在<code>getters</code> 中进行，组件从getters中就可以直接拿到计算好的值。如果所有组件都需要这个计算的话，那就方便多了。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">todos</span>: [</span><br><span class="line">      &#123; <span class="attr">id</span>: <span class="number">1</span>, <span class="attr">text</span>: <span class="string">&#x27;...&#x27;</span>, <span class="attr">done</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">      &#123; <span class="attr">id</span>: <span class="number">2</span>, <span class="attr">text</span>: <span class="string">&#x27;...&#x27;</span>, <span class="attr">done</span>: <span class="literal">false</span> &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">getters</span>: &#123;</span><br><span class="line">    <span class="comment">//也可接收第二参数为其他的getter</span></span><br><span class="line">    <span class="attr">doneTodos</span>: <span class="function"><span class="params">state</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> state.todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.done)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>Getter 会暴露为 <code>store.getters</code> 对象，你可以以属性的形式访问这些值</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">computed: &#123;</span><br><span class="line">    ...mapState([<span class="string">&#x27;title&#x27;</span>, <span class="string">&#x27;userList&#x27;</span>, <span class="string">&#x27;goodsList&#x27;</span>]),</span><br><span class="line">    <span class="comment">// 直接调用getters的doneTodos属性即可</span></span><br><span class="line">    <span class="function"><span class="title">allAge</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.$store.getters.doneTodos</span><br><span class="line">    &#125;</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p>你也可以通过让 getter 返回一个函数，来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">getters: &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  <span class="attr">getTodoById</span>: <span class="function">(<span class="params">state</span>) =&gt;</span> <span class="function">(<span class="params">id</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> state.todos.find(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id === id)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">store.getters.getTodoById(<span class="number">2</span>) <span class="comment">// -&gt; &#123; id: 2, text: &#x27;...&#x27;, done: false &#125;</span></span><br></pre></td></tr></table></figure>

<p>注意，getter 在通过方法访问时，每次都会去进行调用，而不会缓存结果。</p>
<h6 id="5-1-mapgetter"><a href="#5-1-mapgetter" class="headerlink" title="5.1 mapgetter"></a>5.1 mapgetter</h6><p>如果你想将一个 getter 属性另取一个名字，使用对象形式：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"> ...mapGetters(&#123;</span><br><span class="line">  <span class="comment">// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`</span></span><br><span class="line">  <span class="attr">doneCount</span>: <span class="string">&#x27;doneTodosCount&#x27;</span></span><br><span class="line"> &#125;)</span><br><span class="line">     </span><br><span class="line"> <span class="keyword">import</span> &#123; mapGetters &#125; <span class="keyword">from</span> <span class="string">&#x27;vuex&#x27;</span></span><br><span class="line"> <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  <span class="attr">computed</span>: &#123;</span><br><span class="line">  <span class="comment">// 使用对象展开运算符将 getter 混入 computed 对象中</span></span><br><span class="line">    ...mapGetters([</span><br><span class="line">      <span class="string">&#x27;doneTodosCount&#x27;</span>,</span><br><span class="line">      <span class="string">&#x27;anotherGetter&#x27;</span>,</span><br><span class="line">      <span class="comment">// ...</span></span><br><span class="line">    ])</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="6-mutation"><a href="#6-mutation" class="headerlink" title="6.mutation"></a><strong>6.mutation</strong></h5><p>更改 Vuex 的 store 中的状态的唯一方法是提交(<strong>commit</strong>)     <strong>mutation</strong></p>
<p>当需要在store里面操作数据的增删的时候，需要使用mutation属性。</p>
<p>可以在mutation里面添加方法，进行修改数据</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">mutations: &#123;</span><br><span class="line">        <span class="function"><span class="title">addUser</span>(<span class="params">state</span>)</span> &#123;</span><br><span class="line">            state.userList.push(&#123; <span class="attr">userName</span>: <span class="string">&#x27;aaa&#x27;</span>, <span class="attr">age</span>: <span class="number">10</span> &#125;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//在组件里也使用进行调用。</span></span><br><span class="line"><span class="attr">methods</span>: &#123;</span><br><span class="line">        <span class="function"><span class="title">addUser</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="comment">// 使用commit的方式调用</span></span><br><span class="line">            <span class="built_in">this</span>.$store.commit(<span class="string">&#x27;addUser&#x27;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br></pre></td></tr></table></figure>

<p><strong>我们在commit的第二个参数传递数据。这里有个专业的术语叫做【载荷】，只能有一个</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">mutations: &#123;</span><br><span class="line">    <span class="comment">// data接收commit的载荷</span></span><br><span class="line">    <span class="function"><span class="title">addUser</span>(<span class="params">state, data</span>)</span> &#123;</span><br><span class="line">        state.userList.push(&#123;</span><br><span class="line">            <span class="attr">userName</span>: data.name,</span><br><span class="line">            <span class="attr">age</span>: data.age</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//组件里面</span></span><br><span class="line"><span class="attr">methods</span>: &#123;</span><br><span class="line">    <span class="function"><span class="title">addUser</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="comment">// commit的第二个参数填写传递的载荷</span></span><br><span class="line">        <span class="built_in">this</span>.$store.commit(<span class="string">&#x27;addUser&#x27;</span>, &#123;</span><br><span class="line">            <span class="attr">name</span>: <span class="built_in">this</span>.name,</span><br><span class="line">            <span class="attr">age</span>: <span class="built_in">this</span>.age</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p>​    整个应用程序，只有mutations才可以操作state状态。</p>
<p>​    但是注意：</p>
<p>​    <strong>mutations中的属性，必须为纯函数，必须为同步代码。</strong></p>
<p>​    纯函数就是传入相同的参数，得到相同的结果。</p>
<p>​    同步代码就不能是异步的，比如ajax，比如setTimeout等。</p>
<p><strong>在组件中提交 Mutation</strong></p>
<p>你可以在组件中使用 <code>this.$store.commit(&#39;xxx&#39;)</code> 提交 mutation，或者使用 <code>mapMutations</code> 辅助函数将组件中的 methods 映射为 <code>store.commit</code> 调用（需要在根节点注入 <code>store</code>）。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapMutations &#125; <span class="keyword">from</span> <span class="string">&#x27;vuex&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  <span class="attr">methods</span>: &#123;</span><br><span class="line">    ...mapMutations([</span><br><span class="line">      <span class="string">&#x27;increment&#x27;</span>, <span class="comment">// 将 `this.increment()` 映射为 `this.$store.commit(&#x27;increment&#x27;)`</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">// `mapMutations` 也支持载荷：</span></span><br><span class="line">      <span class="string">&#x27;incrementBy&#x27;</span> <span class="comment">// 将 `this.incrementBy(amount)` 映射为 `this.$store.commit(&#x27;incrementBy&#x27;, amount)`</span></span><br><span class="line">    ]),</span><br><span class="line">    ...mapMutations(&#123;</span><br><span class="line">      <span class="attr">add</span>: <span class="string">&#x27;increment&#x27;</span> <span class="comment">// 将 `this.add()` 映射为 `this.$store.commit(&#x27;increment&#x27;)`</span></span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p><strong>Mutation 需遵守 Vue 的响应规则</strong></p>
<p>既然 Vuex 的 store 中的状态是响应式的，那么当我们变更状态时，监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项：</p>
<ol>
<li>最好提前在你的 store 中初始化好所有所需属性。</li>
<li>当需要在对象上添加新属性时，你应该</li>
</ol>
<ul>
<li><p>使用 <code>Vue.set(obj, &#39;newProp&#39;, 123)</code>, 或者</p>
</li>
<li><p>以新对象替换老对象。例如，利用<a target="_blank" rel="noopener" href="https://github.com/tc39/proposal-object-rest-spread">对象展开运算符</a>我们可以这样写：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">state.obj = &#123; ...state.obj, <span class="attr">newProp</span>: <span class="number">123</span> &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h5 id="7-action"><a href="#7-action" class="headerlink" title="7.action"></a><strong>7.action</strong></h5><p>Action 类似于 mutation，不同在于：</p>
<ul>
<li>Action 提交的是 mutation，而不是直接变更状态。</li>
<li>Action 可以包含任意异步操作。</li>
</ul>
<p><em><strong>能操作state的只有mutations，actions也不行。只能调用mutations去操作state。</strong></em></p>
<p>在<strong>action里面</strong>可通过<strong>commit</strong>调用mutation你的数据操纵方法，在组件里的methods里面使用<strong>dispatch</strong>调用action里的方法</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="title">addUserTimeout</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="comment">// 使用dispatch调用actions的属性</span></span><br><span class="line">        <span class="built_in">this</span>.$store.dispatch(<span class="string">&#x27;addUserTimeout&#x27;</span>, &#123;</span><br><span class="line">            <span class="attr">name</span>: <span class="built_in">this</span>.name,</span><br><span class="line">            <span class="attr">age</span>: <span class="built_in">this</span>.age</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象，因此你可以调用 <code>context.commit</code> 提交一个 mutation，或者通过 <code>context.state</code> 和 <code>context.getters</code> 来获取 state 和 getters。当我们在之后介绍到 <a target="_blank" rel="noopener" href="https://vuex.vuejs.org/zh/guide/modules.html">Modules</a> 时，你就知道 context 对象为什么不是 store 实例本身了。</p>
<p>实践中，我们会经常用到 ES2015 的 <a target="_blank" rel="noopener" href="https://github.com/lukehoban/es6features#destructuring">参数解构</a> 来简化代码（特别是我们需要调用 <code>commit</code> 很多次的时候）：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//原来的action</span></span><br><span class="line"><span class="attr">actions</span>: &#123;</span><br><span class="line">    increment (context) &#123;<span class="comment">//这里的context就是上下文，相当于store</span></span><br><span class="line">      context.commit(<span class="string">&#x27;increment&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="comment">//解构的action</span></span><br><span class="line"><span class="attr">actions</span>: &#123;</span><br><span class="line">  increment (&#123; commit &#125;) &#123;</span><br><span class="line">    commit(<span class="string">&#x27;increment&#x27;</span>)<span class="comment">//这个commit就相当于前面的mutation的commit调用</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//action也可以带参数</span></span><br><span class="line"><span class="attr">actions</span>: &#123;</span><br><span class="line">  <span class="comment">//这里的commit和state就是store里面的，products就是带的参数</span></span><br><span class="line">  checkout (&#123; commit, state &#125;, products) &#123;</span><br><span class="line">    <span class="comment">// 把当前购物车的物品备份起来</span></span><br><span class="line">    <span class="keyword">const</span> savedCartItems = [...state.cart.added]</span><br><span class="line">    <span class="comment">// 发出结账请求，然后乐观地清空购物车</span></span><br><span class="line">    commit(types.CHECKOUT_REQUEST)</span><br><span class="line">    <span class="comment">// 购物 API 接受一个成功回调和一个失败回调</span></span><br><span class="line">    shop.buyProducts(</span><br><span class="line">      products,</span><br><span class="line">      <span class="comment">// 成功操作</span></span><br><span class="line">      <span class="function">() =&gt;</span> commit(types.CHECKOUT_SUCCESS),</span><br><span class="line">      <span class="comment">// 失败操作</span></span><br><span class="line">      <span class="function">() =&gt;</span> commit(types.CHECKOUT_FAILURE, savedCartItems)</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同时也可以使用mapAction进行分发action，使用async、await组合action</p>
<p><strong>总结mutations与actiosn的区别：</strong></p>
<p>​    1、commit方法用于调用mutation；dispatch 方法用于调用action；</p>
<p>​    2、mutation 函数必须是纯函数，而且不能有异步代码；action 可以不是纯函数，也可以有异步代码；</p>
<p>​    3、按照上述规则，可以用mutation完成的事情，可以直接调用mutation，mutation不能实现的事情丢给action来完成。</p>
<p>​    4、在action中，当完成异步操作，最终需要修改数据模型时，还是需要通过mutation来完成对数据模型的操作。action不允许直接操作数据模型。</p>
<h5 id="8-module"><a href="#8-module" class="headerlink" title="8.module"></a><strong>8.module</strong></h5><p>由于使用单一状态树，应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时，store 对象就有可能变得相当臃肿。</p>
<p>Vuex 允许我们将 store 分割成<strong>模块（module）</strong>。每个模块拥有自己的 state、mutation、action、getter。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> moduleA = &#123;</span><br><span class="line">  <span class="attr">state</span>: <span class="function">() =&gt;</span> (&#123; ... &#125;),</span><br><span class="line">  <span class="attr">mutations</span>: &#123; ... &#125;,</span><br><span class="line">  <span class="attr">actions</span>: &#123; ... &#125;,</span><br><span class="line">  <span class="attr">getters</span>: &#123; ... &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> moduleB = &#123;</span><br><span class="line">  <span class="attr">state</span>: <span class="function">() =&gt;</span> (&#123; ... &#125;),</span><br><span class="line">  <span class="attr">mutations</span>: &#123; ... &#125;,</span><br><span class="line">  <span class="attr">actions</span>: &#123; ... &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//需要在index.js里导入，上面两个是一个各自单独的文件</span></span><br><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">  <span class="attr">modules</span>: &#123;</span><br><span class="line">    <span class="attr">a</span>: moduleA,</span><br><span class="line">    <span class="attr">b</span>: moduleB</span><br><span class="line">      </span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">store.state.a <span class="comment">// -&gt; moduleA 的状态</span></span><br><span class="line">store.state.b <span class="comment">// -&gt; moduleB 的状态</span></span><br></pre></td></tr></table></figure>

<p>对于模块内部的 mutation 和 getter，接收的第一个参数是<strong>模块的局部状态对象</strong>。</p>
<h6 id="8-1命名空间"><a href="#8-1命名空间" class="headerlink" title="8.1命名空间"></a>8.1命名空间</h6><p>默认情况下，模块内部的 action、mutation 和 getter 是注册在<strong>全局命名空间</strong>的——这样使得多个模块能够对同一 mutation 或 action 作出响应。</p>
<p>如果希望你的模块具有更高的封装度和复用性，你可以通过添加 <code>namespaced: true</code> 的方式使其成为带命名空间的模块。当模块被注册后，它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名，使用的时候会使用这个命名</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="comment">// 开启命名空间</span></span><br><span class="line">    <span class="attr">namespaced</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="attr">state</span>: &#123;</span><br><span class="line">        <span class="attr">title</span>: <span class="string">&#x27;我是首页&#x27;</span>,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><ul>
<li>state就是存数据的</li>
<li>mutation就是改变state里面的数据的同步方法</li>
<li>getter就是方便多个组件获取state里面经过进一步计算后的数据</li>
<li>action就是异步调用mutation间接改变state里面的数据</li>
<li>module就是解决store管理整个项目太大了，数据、方法太臃肿的问题</li>
</ul>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2020/07/19/vue-vuex/">https://chengsong.info/2020/07/19/vue-vuex/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/vue-vuex/">vue vuex</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/07/23/vant,%E6%8F%92%E4%BB%B6,%E6%B7%B7%E5%85%A5,%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%87%E4%BB%A4/"><i class="fa fa-chevron-left">  </i><span>vant,插件,混入,自定义指令</span></a></div><div class="next-post pull-right"><a href="/2020/07/15/vue-router/"><span>vue路由</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>